package util;

import com.jacob.activeX.ActiveXComponent;

import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 * Created by Administrator on 2015/6/15 0015.
 */
public class WordBeanUtil {
    public static final String WORD_PATH = "C:\\Users\\Administrator\\Desktop\\A3\\川改进.docx";
    public static final String NEW_WORD_PATH = "C:\\Users\\Administrator\\Desktop\\A3\\川改进1.docx";

    //代表一个word程序
    private ActiveXComponent MsWordApp = null;
    //代表进行处理的word文档
    private Dispatch document = null;

    public WordBeanUtil() {
        // Open Word if we/'ve not done it already
        if(MsWordApp == null){
            MsWordApp = new ActiveXComponent("Word.Application");
        }
    }

    /**
     * 设置是否在前台打开word程序
     * @param visible
     */
    public void setVisible(boolean visible){
        MsWordApp.setProperty("Visible", new Variant(visible));
        // 这一句作用相同
        // Dispatch.put(MsWordApp, "Visible", new Variant(visible));
    }

    // 创建一个新文档
    public void createNewDocument(){
        // Find the Documents collection object maintained by Word
        // documents表示word的所有文档窗口，（word是多文档应用程序）
        Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
        // Call the Add method of the Documents collection to create
        // a new document to edit
       document = Dispatch.call(documents, "Add").toDispatch();
    }

//    /**
//     * 把选定选定内容设定为替换文本
//     * @param toFindText 查找字符串
//     * @param newText 要替换的内容
//     * @return
//     */
//    public boolean replaceText(String toFindText, String newText) {
//        if (!find(toFindText)){
//            return false;
//        }
//        Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
//        Dispatch.put(selection, "Text", newText);
//        return true;
//    }

    public void printFile() {
        // Just print the current document to the default printer
        Dispatch.call(document, "PrintOut");
    }

    // 保存文档的更改
    public void save() {
        Dispatch.call(document, "Save");
    }



    public void saveFileAs(String filename) {
        Dispatch.call(document, "SaveAs", filename);
    }



    public void closeDocument() {
        // Close the document without saving changes
        // 0 = wdDoNotSaveChanges
        // -1 = wdSaveChanges
        // -2 = wdPromptToSaveChanges
        Dispatch.call(document, "Close", new Variant(0));
        document = null;

    }

    public void closeWord() {
        Dispatch.call(MsWordApp, "Quit");
        MsWordApp = null;
        document = null;
    }



}
